package zilvic.game.room.entity.effect;

import java.awt.Graphics;
import org.duncan.Math2D.Point2D;
import zilvic.game.room.entity.Entity;
import zilvic.game.room.entity.actor.Actor;
import zilvic.resources.ByteMagic;
import zilvic.resources.sprites.Sequence;

/**
 *
 * @author Duncan
 */
public class Effect extends Entity {
    private long maxAge     = Long.MAX_VALUE;
    private long age        = 0;
    private Sequence sequence;

    public Effect(Point2D position) {
        super (position);
    }

    public Effect setSequence(Sequence sequence) {
        this.sequence = sequence;
        return this;
    }

    public Sequence getSequence() {
        return sequence;
    }

    /**
     * Is called each step by the room. If the effect returns true then it is
     * done and should be removed from the room.
     * @param delta The delta time since the last tick.
     * @return True if the timer should be removed. Else false.
     */
    public boolean tick(long delta) {
        age += delta;
        if (age > maxAge) {
            return true;
        }
        return false;
    }

    @Override
    public void paint(Graphics g, byte step) {
        if (sequence != null) {
            getSequence().draw(g, getPosition(), step, Actor.DIRECTION_DOWN);
        }
    }

    /**
     * The format is as follows.
     * 0:  The maxAge (long).
     * 1:  The age (long).
     * 2:  The sequence.
     * @return This effect in bytes.
     */
    @Override
    public byte[] toBytes() {
        return ByteMagic.compressBytes(new byte[][] {
            ByteMagic.longToBytes(maxAge),
            ByteMagic.longToBytes(age),
            sequence.toBytes()});
    }

    @Override
    public void fromBytes(byte[] bytes) {
        byte[][] u = ByteMagic.uncompressBytes(bytes);
        maxAge   = ByteMagic.bytesToLong(u[0]);
        age      = ByteMagic.bytesToLong(u[1]);
        sequence = new Sequence();
        sequence.fromBytes(u[2]);
    }
}
